package services

import (
	"myblog/models"
	"myblog/repositories"
	"myblog/utils"
)

type ArticleService struct {
	repo *repositories.ArticleRepository
}

func NewArticleService(repo *repositories.ArticleRepository) *ArticleService {
	return &ArticleService{repo: repo}
}

func (s *ArticleService) CreateArticle(title, content string, published bool) (*models.Article, error) {
	slug := utils.GenerateSlug(title)
	excerpt := utils.GenerateExcerpt(content, 100)
	
	article := &models.Article{
		Title:     title,
		Content:   content,
		Slug:      slug,
		Excerpt:   excerpt,
		Published: published,
	}
	
	if err := s.repo.Create(article); err != nil {
		return nil, err
	}
	
	return article, nil
}

func (s *ArticleService) UpdateArticle(id uint, title, content string, published bool) (*models.Article, error) {
	article, err := s.repo.FindByID(id)
	if err != nil {
		return nil, err
	}
	
	article.Title = title
	article.Content = content
	article.Published = published
	
	// 如果标题改变了，重新生成slug
	if title != article.Title {
		article.Slug = utils.GenerateSlug(title)
	}
	
	// 重新生成摘要
	article.Excerpt = utils.GenerateExcerpt(content, 100)
	
	if err := s.repo.Update(article); err != nil {
		return nil, err
	}
	
	return article, nil
}

func (s *ArticleService) GetArticleBySlug(slug string) (*models.Article, error) {
	return s.repo.GetBySlug(slug)
}

func (s *ArticleService) GetAllArticles() ([]models.Article, error) {
	return s.repo.GetAllPublished()
}

func (s *ArticleService) GetAllArticlesForAdmin() ([]models.Article, error) {
	return s.repo.GetAll()
}

func (s *ArticleService) GetArticleByID(id uint) (*models.Article, error) {
	return s.repo.FindByID(id)
}

func (s *ArticleService) DeleteArticle(id uint) error {
	return s.repo.Delete(id)
}